/**@file server_ipc.c
 * @note 
 * @brief  测试代码
 * 
 * @author   luoxi11
 * @date     20220707
 * @version  V1.0.0
 * 
 * @note ///Description here 
 * @note History:        
 * @note     <author>   <time>    <version >   <desc>
 * @note  
 * @warning  
 */
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>

#include "errno.h"

#ifndef FOREVER
#define FOREVER for(;;)
#endif


typedef struct msg
{
	char command;                     /* 接收到数据标志位，根据该标志位去判断是否更新数据 */
}report_server_msg;


typedef struct msg_r
{
   char open_diald;                   /* 接收到数据标志位，根据该标志位去判断是否更新数据 */
}recieve_server_msg;



report_server_msg reportmsg;
recieve_server_msg receivemsg;


void server_sharemsg()
{
	int server_sockfd = -1;
	int client_sockfd = -1;
	int client_len = 0;
	int bind_cnn= -1;
	int read_cnn= -1;
	struct sockaddr_in server_addr;
	struct sockaddr_in client_addr;
	
	server_sockfd = socket(AF_INET, SOCK_STREAM, 0);        /* 创建流套接字 */
	if(-1 == server_sockfd)
	{
		printf("socket creat error\n");
	}
	/* 设置服务器接收的连接地址和监听的端口 */
	server_addr.sin_family = AF_INET;                       /* 指定网络套接字 */
	server_addr.sin_addr.s_addr = htonl(INADDR_ANY);        /* 接受所有IP地址的连接 */
	server_addr.sin_port = htons(9736);                     /* 绑定到9736端口 */
    bind_cnn = bind(server_sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr)); /* 绑定（命名）套接字 */
	if(-1 == bind_cnn)
	{
		printf("bind creat error\n");
	}

	listen(server_sockfd, 5);        /* 创建套接字队列，监听套接字 */
	signal(SIGCHLD, SIG_IGN);        /* 忽略子进程停止或退出信号 */
	client_len = sizeof(client_addr);
	char connect_flag = 0;
	reportmsg.command = 0;

	FOREVER
	{
		/* 接受连接，创建新的套接字 */
		if(0 == connect_flag)
		client_sockfd = accept(server_sockfd, (struct sockaddr*)&client_addr, &client_len);
		if(client_sockfd < 0)
		{
		    printf("accept socket %d\n", client_sockfd);
		    printf("accept error is %d\n", errno); 
		    close(client_sockfd);		 
		}
		else
		{
			reportmsg.command ++;
			if(reportmsg.command > 10)
			{
				reportmsg.command = 0;
			}
			connect_flag = 1;
			
			read_cnn = read(client_sockfd, &receivemsg, sizeof(recieve_server_msg));    /* 读取客户端发过来的信息，处理信息，再发送给客户端 */
			if(-1 == read_cnn)
			{
              printf("read creat error\n");
			}
			else
			{
             printf("receivemsg.open_diald is %d\n", receivemsg.open_diald);
			}
			sleep(1);
			write(client_sockfd, &receivemsg, sizeof(report_server_msg));
		}
		sleep(3);	
	}
}


int main(int argv, char *argc[])
{
	server_sharemsg();
	return 0;
}